Language basics
SCL is a functional programming language that is based on lambda calculus.
Lambda calculus is a minimal but still Turing complete language with three
constructions:
- Variables
- Function applications
- Function definitions (lambda terms)
These are also the most central elements of SCL and most of the other constructions are only
syntactic sugar on top of lambda calculus.
SCL syntax is very close to the syntax of Haskell programming language and many tutorials
on Haskell apply also to SCL. The main difference between the languages is the evaluation strategy:
Haskell evaluates terms lazily, SCL strictly. Unlike Haskell, SCL allows side-effects during
function application, but controls them with effect typing. In this respects, it behaves similarly
to ML or OCaml.
SCL inherits the following philosophy from Haskell and other programming languages in functional paradigm:
- Avoid stateful programming
- Express mathematical problems in mathematical syntax
- Expressive types prevent runtime errors
This section gives a walkthrough for the most importatant constructs of SCL language.
Literals
SCL supports the following types of constant expressions:
Integers
3423
Floating point numbers
1.2
2.6e-4
String literals
SCL supports single-line strings (enclosed in quotes)
"Single line text"
"Text\nwith\nmultiple lines"
and multi-line strings (enclosed in triple quotes)
"""Text
with
multiple lines"""
Single-line strings may contain escaped characters (\n line feed, \t tabulator, \r carriage return, \uxxxx unicode character,
\<character> the character without the first \).
Character literals
't'
'\''
Boolean constants are written as True and False although they are not technically literals (but constructors).
Identifiers
Variable and constant names start with lower case letter followed by letters, digits, _ and '.
It customary to write multi-word concepts with camel case convention, for example
printError or importA5Model.
The following names are reserved and cannot be used as identifiers:
as, by, class, constraint, data, deriving, do, effect, else, enforce, extends, forall,
hiding, if, import, importJava, in, include, infix, infixl, infixr, instance, let, match,
mdo, rule, select, then, transformation, type, when, where, with.
A few words depend on the features a module enables in its header (see
1.16 Module system): edo is reserved only with the edo feature and ruleset only
with the chr feature, while chr turns rule and transformation into ordinary
identifiers. abstract rule, mapping relation, select first and select distinct are
two-word keywords; abstract, mapping, relation, first and distinct on their own
are ordinary identifiers.
Identifiers starting with upper case letter are constructors and they can be defined only
together with the new data types. Examples: True, False and Nothing.
Function applications
A function is applied by writing the function and its parameters consecutively.
sin pi
max 2 5
A parameter needs to be closed in parenthesis if it is not a variable, literal, or an expression starting
with if, let, do, etc.
sqrt (x*x + y*y)
atan2 (sin a) (cos a)
For example
sqrt x*x + y*y
is evaluated as
(sqrt x)*x + y*y
because the function application has higher precedence than
any binary operator.
Parentheses are also needed around negation
sin (-1.42)
because otherwise the expression is tried to compile as
sin - 1.42
causing a compilation error because sin and 1.42 are not
compatible for subtraction.
Binary operators
Binary operators are normal functions that are just written between their parameters:
1 + 2
Each binary operator can be converted into ordinary function by putting parentheses around it
(+) 1 2
Similarly an ordinary function can be converted into binary operator by putting backticks (`) around it.
3.4 `max` 4.5
Binary operators have precedences that determines how multiple consecutive binary operators
are compiled. For example
1*2+3*4+5*6
is evaluated as
((1*2) + (3*4)) + (5*6)
Variable definitions
Variables are defined by syntax
variableName = variableValue
for example
g = 9.80665
Defined variable values are available in the
consecutive expressions:
a = 13
b = 14
a*b
Function definitions
Functions are defined by writing a function application
in the left-hand side of the equation:
increaseByOne x = x+1
Defined functions are available in the consecutive expressions:
increaseByOne 13
Conditional expressions
Conditional expressions are written in the form:
if <condition> then <successBranch> else <failureBranch>
The else branch is always mandatory. Leaving it out gives the misleading error
Unclosed parentheses.
abs x = if x > 0
then x
else -x
Recursion
A function definition can refer to itself. For example, the Euclidean algorithm for
computing the greatest common divisor of two integers can be written as:
gcd a b = if a > b
then gcd b a
else if a == 0
then b
else gcd (b `mod` a) a
Local definitions
Variable and function definitions can be written as a part of larger
expression. There are three language constructs for this purpose:
let <definitions> in <result>
do <definitions>
<result>
<definition> where <definitions>
They are quite similar and
it is usually just a stylistic choice which one to use.
If you are only defining local variables that are needed in a subexpression
and their computation does not have side-effects (or has only reading effects),
the most natural choice is let-construct that allows you to define
variables between let and in and used the variables in the expression following in:
distance (x1,y1) (x2,y2) = let dx = x1-x2
dy = y1-y2
in sqrt (dx*dx + dy*dy)
Let-expressions can be freely embedded in other expressions:
"""
Finds a root of f given neg and pos with assumption that
f neg < 0
and
f pos > 0
"""
bisectionMethod f neg pos =
let middle = (neg+pos)*0.5 in
if abs (neg-pos) < 1e-9
then middle
else let middleVal = f middle in
if middleVal < (-1e-9)
then bisectionMethod f middle pos
else if middleVal > 1e-9
then bisectionMethod f neg middle
else middle
Another construction allowing local variable bindings is do. The value of the whole
do-expression is determined by the last expression in the do-block. This construct
should be used when there are side-effects involved and you want to mix variable bindings
with function applications that ignore their result:
createModel parent name = do
model = newResource ()
claim model L0.InstanceOf SIMU.Model
claimRelatedValue model L0.HasName name
claim model L0.PartOf parent
model
The final binding construction is where that locates variable definitions after the position the variables are used. It differs from let and do because
it does not define an expression but is always related to some other definition.
The benefit is that the same where -block can be used by multiple
different guarded definitions:
"""
Returns all solutions of the quadratic equation a*x^2 + b*x + c = 0.
"""
solveQuadratic :: Double -> Double -> Double -> [Double]
solveQuadratic a b c
| discriminant < 0 = []
| discriminant > 0 = let sqrtDisc = sqrt discriminant
in [ (-b-sqrtDisc)/(2*a)
, (-b+sqrtDisc)/(2*a) ]
| otherwise = [ -b / (2*a) ]
where
discriminant = b*b - 4*a*c
The order of the definitions in a block matters in one respect. A function definition can
use the function definitions next to it, whether they come before or after it. A
definition without parameters, such as base = 10, splits the block: the definitions
above it cannot use it or anything below it. Put such values above the functions that use
them:
digits n = loop n []
where
base = 10
loop k acc = if k < base
then [k] + acc
else loop (k `div` base) ([k `mod` base] + acc)
With base = 10 below loop, the compiler would report Couldn't resolve base. The top
level of a script follows the same rule, see 1.18 Modules vs scripts.
Functions taking other functions as parameters
In SCL, functions are ordinary values that can be stored to variables and manipulated.
For example, writing only the function name to the console produces:
> sin
<value of type Double -> <a> Double>
We can define for example a numerical derivative operation
epsilon = 1e-9
der f x = (f (x + epsilon) - f (x - epsilon)) / (2*epsilon)
Now,
> der sin 0
1.0
> der exp 1
2.7182818218562943
Anonymous function definitions
Functional style of programming favors lots of small functions.
Giving a name for all of them becomes quickly tedious and
therefore functions can be defined also anonymously. For
example
\x -> x+1
defines a function that increases its parameter by one.
Thus
(\x -> x+1) 13
returns 14.
Assuming that the function der is defined as above
> der (\x -> x*x) 2
4.000000330961484
An anonymous function can take several parameters, and its parameters can be patterns:
(\x y -> x + y) 1 2 // 3
(\(a, b) -> a * b) (3, 4) // 12
To match the parameter against several alternatives, use \match (see
Match expressions below).
Partial function application
It is possible to give a function less parameters that
it accepts:
> der sin
<value of type Double -> <a> Double>
Such a partial application creates a function that expects
the missing parameters:
> myCos = der sin
> myCos 0
> myCos pi
-1.000000082740371
It is possible to partially apply also binary operators giving
only one of its parameters. Such an application must always
be enclosed in parentheses
lessThanOne = (< 1)
greaterThanOne = (1 <)
Pattern matching
The constructors are special kind of values and functions
that can be used in the left-hand side of the function and
value definitions. Most common constructors are
the tuple constructors (), (,), (,,), ...:
toPolarCoordinates (x,y) = (sqrt (x*x + y*y), atan2 y x)
toRectangularCoordinates (r,angle) = (r*cos angle, r*sin angle)
Other constructors are used like functions, but the name
of the constructor is capitalized, for example Just and Nothing:
fromMaybe _ (Just v) = v
fromMaybe default Nothing = default
This example demonstrates also some other features. A function
can be defined with multiple equations and the first matching
equation is used. Also, if some parameter value is not used,
it may be replaced by _.
Guard expressions
A function body can be conditionally selected using guard expressions. Guards are written
with | after the argument patterns; the first guard whose condition is True is chosen.
otherwise is an alias for True and acts as a catch-all:
gcd :: Integer -> Integer -> Integer
gcd 0 b = b
gcd a b
| a > b = gcd b a
| otherwise = gcd (mod b a) a
Guards may appear in a function with multiple equations; each equation can have its own
guards. If none of the guards of an equation holds, the next equation is tried.
A guard may consist of several comma-separated conditions, all of which must hold:
classify x
| x > 0, x < 10 = "digit"
| otherwise = "other"
Match expressions
Pattern matching is not limited to function definitions. A match expression matches a
value against a list of alternatives, each written as pattern -> result:
match <expression> with
<pattern1> -> <result1>
<pattern2> -> <result2>
...
The alternatives are tried from top to bottom and the result of the first matching one
is the value of the whole expression. Any pattern that can appear in a function
definition can be used, and the names it binds are visible in that alternative only:
describe :: Maybe Integer -> String
describe m = match m with
Just 0 -> "zero"
Just n -> "the number \(n)"
Nothing -> "nothing"
The alternatives must start at the same column, as with the statements of a do block
(see Indentation below). Alternatively they can be enclosed in braces and separated
by semicolons, which fits a short match on one line:
match (1, 2) with { (0, _) -> "starts with zero"; _ -> "something else" }
An alternative can have guards. They are written as in function definitions, but with
-> instead of =. A guard may consist of several comma-separated conditions, all of
which must hold. If none of the guards of an alternative holds, matching continues with
the next alternative:
sizeClass :: (Integer, Integer) -> String
sizeClass dims = match dims with
(w, h) | w <= 0 || h <= 0 -> "empty"
| w * h > 1000, w == h -> "large square"
| w * h > 1000 -> "large"
_ -> "small"
If no alternative matches, evaluation fails at run time with
org.simantics.scl.runtime.exceptions.MatchingException. End the alternatives with a
catch-all _ pattern unless every possible value is covered.
\match defines an anonymous function that matches its single argument directly, so
\match ... is the same as \x -> match x with ...:
lookupOrZero :: Maybe Integer -> Integer
lookupOrZero = \match
Just v -> v
Nothing -> 0
An alternative can end with a where block, as an equation can. Its definitions are
visible in the guards and in the results of that alternative:
classify :: Maybe Integer -> String
classify m = match m with
Just v
| v > limit -> "big"
| v > 0 -> "positive"
where
limit = 10
Just v -> "non-positive"
Nothing -> "nothing"
As without a where block, matching continues with the next alternative when none of
the guards holds, and the same holds for the equations of a function. The where block
may also contain destructuring bindings such as (a, b) = e; a value that does not fit
such a pattern fails with a MatchingException, it does not move on to the next
alternative.
Users familiar with Haskell should note that SCL has no case ... of; match ... with
takes its place.
Naming conventions
The SCL compiler enforces naming conventions:
- Types and constructors must start with an upper-case letter:
Integer, Maybe,
Just, Nothing, MyRecord.
- Variables and functions must start with a lower-case letter:
x, myFunction,
radius.
Violating these conventions is a compilation error, not a style warning.
Indentation
SCL uses indentation to delimit blocks, similarly to Python or Haskell. The rule is simple:
a new definition or statement at the same level of indentation as the preceding one
is treated as a sibling; a line indented further is a continuation.
In let and do blocks, each binding starts at the same column as the first binding:
f x = let
a = x + 1
b = a * 2
in a + b
g x = do
a = x + 1
b = a * 2
a + b
In where clauses, the definitions start at the column of the first definition after
where, which may be on the same line as where or on the next one. They must be
indented further than the definition the where belongs to; indenting them past the
where keyword, as below, is the usual style:
solveQuadratic a b c
| discriminant < 0 = []
| otherwise = [ -b / (2*a) ]
where
discriminant = b*b - 4*a*c
Semicolons can be used instead of newlines+indentation to write multiple statements on one
line:
do { a = 1; b = 2; a + b }
String interpolation
Inside a double-quoted string literal, \(expr) embeds the value of expr directly into
the string. A String value is inserted as it is, without quotes; any other value is
converted as show would convert it, so "\(["a"])" gives ["a"] with the quotes:
name = "world"
greeting = "Hello, \(name)!" // "Hello, world!"
area = "Area = \(pi * r * r)"
Multi-line strings use triple quotes """...""". Inside triple-quoted strings, no escape
sequences are processed — backslashes and quotes appear literally:
path = """C:\Users\Alice\Documents"""
multiLine = """Line one
Line two
Line three"""
The one exception is interpolation: \(expr) works in triple-quoted strings too, so
"""Total: \(1 + 2)""" gives Total: 3.
Pattern matching — advanced details
The @-operator
The @ operator binds the entire matched value to a name while still destructuring it.
This is useful when you need both the whole structure and its components:
describeList :: [Integer] -> String
describeList xs@[first, _] = "Pair starting with \(first), full: \(xs)"
describeList [] = "Empty list"
describeList xs = "List of length \(length xs)"
List patterns
A list pattern such as [], [x] or [first, _] matches only lists of exactly that
length. Unlike Haskell lists, SCL lists are not built from cons cells, so there is no
Haskell-style x:xs pattern for splitting a list into its head and tail; use xs!0 and
drop 1 xs instead.
View patterns
A view pattern (f -> pattern) applies the function f to the value and matches the
result against pattern:
swapPath :: String -> String
swapPath (split "/" -> [a, b]) = "\(b)/\(a)"
swapPath s = s
swapPath "usr/bin" // "bin/usr"
swapPath "a/b/c" // "a/b/c"
describe :: [Integer] -> String
describe (length -> 0) = "empty"
describe _ = "not empty"
Wildcard _
_ matches any value and binds nothing. It may appear any number of times in one pattern,
and each occurrence may match a different value:
third (_, _, x) = x
ignoreFirst (_, b) = b
Pitfall: patterns always introduce new bindings
A name in a pattern position always introduces a new local binding — it never tests
equality against an existing variable. For example:
// WRONG intention: test whether argument equals the existing `target`
checkTarget target x = match x with
target -> True // this binds a new `target`, shadowing the outer one!
_ -> False
Use a guard instead:
checkTarget target x
| x == target = True
| otherwise = False
Destructuring bindings: console and scripts vs. modules
A definition whose left-hand side is a pattern, such as (a, b) = (1, 2), is a
destructuring binding. On the console and in SCL scripts it binds every variable of the
pattern:
> (a, b) = (1, 2)
> a + b
3
> Just h = Just "hi"
> h
"hi"
The match happens when the statement runs, so a pattern that does not fit its value fails
with a MatchingException and binds nothing.
A module is more restricted: a destructuring binding at the top level of a module is
rejected with Illegal left hand side of the definition. Inside a module, use one only in
a let or where block:
// In a module:
distance p = sqrt (x*x + y*y)
where
(x, y) = p
See 1.18 Modules vs scripts for the details.
|